<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>12.自定义指令改变组件颜色</title>
    <style>
      #app {
        width: 200px;
        height: 200px;
        background-color: #ccc;
      }
    </style>
  </head>
  <body>
    <div id="app" v-color></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
    <script>
      Vue.directive("color", {
        inserted(el) {
          el.onclick = function () {
            el.style.backgroundColor = `rgb(${parseInt(
              Math.random() * 256
            )},${parseInt(Math.random() * 256)},${parseInt(
              Math.random() * 256
            )})`;
          };
        },
      });
      new Vue({
        el: "#app",
        data: {
          msg: "hello",
          red: "",
        },

        directives: {
          blue: {
            inserted(el) {
              el.style.backgroundColor = "blue";
            },
          },
        },
      });
    </script>
  </body>
</html>
